package com.project.bookstore.common.utils;

import org.apache.commons.io.input.ReversedLinesFileReader;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;

public class GetBookCategoryFromCategoryStr {
    /**
     * 标题两侧分割符
     */
    public static final String SPLIT_CHAR = "*";
    String categoryLevel3;

    /**
     *  @param categoryLevel3 需要解析的类别字符串
     */
    public GetBookCategoryFromCategoryStr(String categoryLevel3) {
        this.categoryLevel3 = categoryLevel3;
    }

    /**
     * 获取当前目录的资源文件根目录的 category.sql 文件
     * @return 当前目录的资源文件根目录文件
     * @throws FileNotFoundException 当前目录的资源文件根目录没有 category.sql 文件
     */
    public static File getFile() throws FileNotFoundException {
        String path = ResourceUtils.getURL("classpath:").getPath();
        String fileName = "category.sql";
        File file = new File(path + fileName);
        if (!file.isFile()){
            File[] files = new File(path).listFiles();
            for (int i = 0; i < Objects.requireNonNull(files).length; i++) {
                System.out.println("当前目录("+path+")下的文件如下");
                System.out.println(files[i].getName());
            }
            System.out.println("未找到 " + fileName + " 文件");
            return null;
        }
        return file;
    }

    /**
     * 解析为 sql 语句
     * @param file 资源文件根目录的 category.sql 文件
     * @return sql 语句
     * @throws IOException
     */
    public String getCategoryByRE2(File file) throws IOException {

        categoryLevel3 = categoryLevel3.replace("\n\n", "|");
        String[] categoryLevel3s = categoryLevel3.split("\\*");
        int num = categoryLevel3s.length / 2;
        String[] category3Template = new String[num];
        String[] categoryLevel2s = new String[num];
        StringBuilder category1builder = new StringBuilder();
        for (int i = 0; i < num; i++) {
            category3Template[i] = categoryLevel3s[i * 2 + 1].trim();
            categoryLevel2s[i] = categoryLevel3s[i * 2].trim();
            category1builder.append(categoryLevel3s[i * 2].trim());
            if (i != num - 1)
                category1builder.append("/");
        }
        String categoryLevel1 = category1builder.toString();
        categoryLevel3s = category3Template;
        System.out.println("==========一级标题=============");
        System.out.println(categoryLevel1);
        System.out.println("==========二级标题=============");
        System.out.println(Arrays.toString(categoryLevel2s));
        System.out.println("==========三级标题=============");
        System.out.println(Arrays.toString(categoryLevel3s));
        StringBuilder sqlBuilder = new StringBuilder();
        //读取 sql 最后一行 获取最后一个 ID
        ReversedLinesFileReader reversedLinesFileReader = new ReversedLinesFileReader(file, StandardCharsets.UTF_8);
        String lastLine = reversedLinesFileReader.readLine();
        reversedLinesFileReader.close();
        //sql语句参数
        int id =0;
        if (lastLine != null) {
            id = Integer.parseInt(lastLine.substring(lastLine.indexOf("(") + 1, lastLine.indexOf(",")));
        }
        int l2ParentId = id + 1;
        int l3Id = l2ParentId + num;
        //1是 0不是
        int isParent = 0;
        String categorySqlLevel1 = " (" + (++id) + ",'" + categoryLevel1 + "',0,1,NULL,0,'http://a.jpg',1,1,1,'2022-04-06 14:16:24','2022-04-06 14:16:32'),\n";
        //添加一级分类
        sqlBuilder.append("\n").append(categorySqlLevel1);
        String categorySqlLevel2;
        String categorySqlLevel3;
        for (int i = 0; i < categoryLevel2s.length; i++) {
            categorySqlLevel2 = " (" + (l2ParentId + 1 + i) + ",'" + categoryLevel2s[i].trim() + "'," + l2ParentId + ",2,NULL,0,'http://a.jpg',1,1,1,'2022-04-06 14:16:24','2022-04-06 14:16:32'),\n";
            //添加二级分类
            sqlBuilder.append("\n").append(categorySqlLevel2);

            categorySqlLevel3 = (l2ParentId + i + 1) + ",3,NULL,0,'http://a.jpg',1," + isParent +
                    ",1,'2022-04-06 14:16:24','2022-04-06 14:16:32'),";
            if (!sqlBuilder.toString().endsWith("("))
                sqlBuilder.append("(");
            String subCategoryLevel3 = categoryLevel3s[i];
            String[] split = subCategoryLevel3.split("\\|");
            for (int j = 0; j < split.length; j++) {
                sqlBuilder.append(++l3Id).append(",'").append(split[j].trim()).append("',")
                        .append(categorySqlLevel3);
                if (j != split.length - 1)
                    sqlBuilder.append("\n(");
            }
        }
        System.out.println("-------------sql: -----------------");
        System.out.println(sqlBuilder);
        return sqlBuilder.toString();
    }

    /**
     * 将 sql 语句输出到对应文件
     * @param file
     * @param sql
     * @throws IOException
     */
    public void writeSqlToFile(File file,String sql) throws IOException {
        //输出到 sql 文件夹
        BufferedWriter bufferedWriter = new BufferedWriter(
                new OutputStreamWriter(
                        new FileOutputStream(file, true), StandardCharsets.UTF_8));
        bufferedWriter.write(sql);
        bufferedWriter.close();
    }
}
